package uk.ac.aber.paws.server.net;

import java.net.*;
import java.util.logging.Level;

import uk.ac.aber.paws.server.config.ConfigManager;
import uk.ac.aber.paws.server.core.PAWSServer;
import uk.ac.aber.paws.server.dataobjects.ComputerRecord;
import uk.ac.aber.paws.server.util.TextManip;

/**
 * @author Rob Johnson, Aberystwyth University
 * @email rob.johnson@aber.ac.uk
 * @date 21st May 2012
 * 
 * WakeOnLan.java
 * 
 * This class sends WOL packets to the client
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
public class WakeOnLan {
    

    /**
     * Performs an actual wake up on the client computer/
     * @param fqdn The computer to be woken up
     */
    public static void performWakeUpOnComputer(String fqdn) {
		
		ComputerRecord thisComputer = new ComputerRecord(fqdn); 
		
		boolean success = WakeOnLan.wakeup(ConfigManager.getProperty("app.net.wol.broadcastaddr"), thisComputer.getMACAddress(), Integer.parseInt(ConfigManager.getProperty("app.net.wol.port")));

		if (success) {
			PAWSServer.LOG_FILE.log(Level.ALL,"Wake-on-LAN packet sent.");
		}
		else {
			PAWSServer.LOG_FILE.log(Level.ALL,"Failed to send Wake-on-LAN packet: ");
		}
	}
    
    /**
     * Code to send the actual WOL packet
     * @param ipStr The broadcast IP address
     * @param macStr The MAC address of the NIC on the client
     */
    public static boolean wakeup(String ipStr, String macStr, int port) {
        
        try {
        	
            byte[] macBytes = getMacBytes(macStr);
            byte[] bytes = new byte[6 + 16 * macBytes.length];
            for (int i = 0; i < 6; i++) {
                bytes[i] = (byte) 0xff;
            }
            for (int i = 6; i < bytes.length; i += macBytes.length) {
                System.arraycopy(macBytes, 0, bytes, i, macBytes.length);
            }
       
            InetAddress address = InetAddress.getByName(ipStr);
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, port);
            DatagramSocket socket = new DatagramSocket();
            socket.send(packet);
            socket.close();
            

            return true;
        }
        catch (Exception e) {
    
            e.printStackTrace();
        }
        
        return false;
    }
    
    /**
     * Converts the MAC address into a byte array
     * @param macStr The MAC address
     * @return Returns the byte array
     * @throws IllegalArgumentException
     */
    private static byte[] getMacBytes(String macStr) throws IllegalArgumentException {
        byte[] bytes = new byte[6];
        String[] hex = macStr.split("(\\:|\\-)");
        if (hex.length != 6) {
            throw new IllegalArgumentException("Invalid MAC address.");
        }
        try {
            for (int i = 0; i < 6; i++) {
                bytes[i] = (byte) Integer.parseInt(hex[i], 16);
            }
        }
        catch (NumberFormatException e) {
            throw new IllegalArgumentException("Invalid hex digit in MAC address.");
        }
        return bytes;
    }
    
   
}